﻿package com.easyfun.healthmagicbox.gallary; 

import java.sql.SQLException;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;

import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.pojo.Picture;
import com.easyfun.healthmagicbox.util.URIConverter;
import com.j256.ormlite.dao.Dao;

/**
 * 
 * @author 空山不空
 * 图片资源类
 */
public class ImageSource implements DatabaseAccess {
	private static ImageSource instance = null;
	String personID;
	
	public static ImageSource getInstance(Context context)
	{
		if (instance == null)
		{
			instance = new ImageSource(context);
		}
		return instance;
		
	}
	
	Context context;
	List<Picture> pictures;
	private ImageSource(Context context)
	{
		this.context = context;
	}
	@Override
	public DatabaseHelper getHelper(Context context) {
		return DatabaseAccessImplementation.getInstance().getHelper(context);
	}
	//图片资源
//	 static Integer[] mThumbIds = {
//	    		R.drawable.p1,R.drawable.p2,R.drawable.p3,
//	            R.drawable.p4,R.drawable.p5, R.drawable.p6,
//	            R.drawable.p7, R.drawable.p8,R.drawable.p9,
//	            R.drawable.p10
//	    };
	
	public int imageCount(String personID)
	{
		this.personID = personID;
		try {
			Dao<Picture, Integer> picDao = this.getHelper(context).getPictureDao();
			pictures = picDao.queryBuilder()
				    
				    .where().eq("personID", personID).query();
			return pictures.size();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public Bitmap imageAt(int loc,String personID)
	{
		if (this.personID!= personID)
		{
			imageCount(personID);
		}
		Picture pic = pictures.get(loc);
		if (pic == null)
		{
			return null;
		}
		return URIConverter.getPictureFromAppSDCard(context,personID, pic.getFilename());
		
	}
	
	public int deleteImageAt(int loc)
	{
		
		Picture pic = pictures.get(loc);
		if (pic == null)
		{
			return -1;
		}
		try {
			Dao<Picture, Integer> picDao = this.getHelper(context).getPictureDao();
			picDao.delete(pic);
			pictures.remove(loc);
			URIConverter.deletePictureFromAppSDCard(context, pic.getFilename());
			return pic.getSyncid();
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		}
	}
 }